package com.fengzai.myproxy;

import java.io.*;

/**
 * Created by  峰仔  on 2017-08-03
 */
public class MyClassLoader extends ClassLoader {
    File baseDir;

    public MyClassLoader() {
        String path = MyClassLoader.class.getResource("").getPath();
        baseDir = new File(path);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //jvm加载.class到内存
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        if (null != baseDir) {
            File classFile = new File(baseDir, name.replaceAll("\\.", "/") + ".class");
            if (classFile.exists()) {
                try (FileInputStream in = new FileInputStream(classFile);
                     ByteArrayOutputStream out = new ByteArrayOutputStream();
                ) {
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = in.read(bytes)) != -1) {
                        out.write(bytes, 0, len);
                    }
                    return defineClass(className, out.toByteArray(), 0, out.size());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    //将生成的.java和.class删除  消除痕迹   做到无感知代理
                    classFile.delete();
                }

            }
        }
        return null;
    }
}
